package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;


@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService service;


    @PostMapping("/add")
    public R saveShoppingCart(@RequestBody ShoppingCart shoppingCart) {

        //判断当前点的菜，购物车中是否已经存在
        //select * from shopping_cart where dish_id = ? and user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        if (shoppingCart.getSetmealId() != null) {
            qw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        } else {
            qw.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        }
        qw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        ShoppingCart one = service.getOne(qw);
        if (one == null) {
            //如果不存在，没有点过，新增
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            service.save(shoppingCart);
            return R.success(shoppingCart);
        }
        //如果存在，说明点过了，数量加一
        one.setNumber(one.getNumber() + 1);
        service.updateById(one);
        return R.success(one);
    }
    @GetMapping("/list")
    public R list(){
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        List<ShoppingCart> list = service.list(wrapper);
        return R.success(list);
    }
    @PostMapping("sub")
    public R subShoppingCart(@RequestBody ShoppingCart shoppingCart){
        // number-1
        //update shopping_cart set number = ? where (dish_id = ? 或者 setmeal_id = ?)
        // and user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        if(shoppingCart.getDishId() != null){  //菜品
            qw.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }else {  //套餐
            qw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        qw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        ShoppingCart one = service.getOne(qw);
        one.setNumber(one.getNumber()-1);

        if(one.getNumber() == 0){ //菜或套餐不要了
            //delete from xx where id = ?
            service.removeById(one.getId());
        }else {
            service.updateById(one);
        }
        return R.success(one);
    }
    @DeleteMapping("/clean")
    public R deleteShoppingCart(){
        service.removeById(BaseContext.getCurrentId());
        return R.success("删除成功");
    }  


}
